<script setup lang="ts">
import { defineProps, inject, ref, watch } from 'vue'
import { anyFuncCall } from '/@/utils'

const tableScopeEvents = inject<any>('tableScopeEvents')

const props = defineProps({
  options: { type: Array as PropType<YTableOperaOption[]>, required: true }
})

type ShowOption = YTableOperaOption & {
  _show: boolean
}

const isUpdate = ref(false)

const showOptions = ref<ShowOption[]>([])
const moreOptions = ref<ShowOption[]>([])

watch(isUpdate, async () => {
  showOptions.value = props.options.filter(s => !s.more).map(s => ({ ...s, _show: true })) as ShowOption[]

  showOptions.value.forEach(s => {
    if (typeof s.visible === 'function') {
      s._show = false
      anyFuncCall(s.visible).then(res => {
        s._show = res as boolean;
      })
    } else {
      if (s.visible === false) {
        s._show = false
      }
    }
  })

  moreOptions.value = props.options.filter(s => s.more).map(s => ({ ...s, _show: true })) as ShowOption[]

  moreOptions.value.forEach(s => {
    if (typeof s.visible === 'function') {
      s._show = false
      anyFuncCall(s.visible).then(res => {
        s._show = res as boolean;
      })
    } else {
      if (s.visible === false) {
        s._show = false
      }
    }
  })
}, { immediate: true })



const handClick = (item: YTableOperaOption) => {
  if (item.trigger) {
    tableScopeEvents.emit('opera-click', item.trigger)
  }
}

const update = () => {
  isUpdate.value = !isUpdate.value
}

tableScopeEvents.on('update-operas', () => {
  update()
})


</script>
<template>
  <el-button-group class="y-table-operas" style="height:32px">
    <el-button v-for="(item, index) of showOptions" :key="index" v-bind="item" @click="handClick(item)"
      v-show="item._show">
      {{ item.title }}
    </el-button>

    <el-dropdown v-if="moreOptions.filter(s => s._show).length">
      <el-button style="border-left: 1px solid var(--el-border-color);">
        <IconifyIconOffline icon="arrow-right-bold" />
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <template v-for="item of moreOptions.filter(s => s._show)">
            <el-dropdown-item v-if="item._show" v-bind="item" @click="handClick(item)">{{
                item.title
            }}
            </el-dropdown-item>
          </template>

        </el-dropdown-menu>
      </template>
    </el-dropdown>


  </el-button-group>
</template>